import java.util.Random;
import java.util.concurrent.*;

/**
 * author: MaHX
 * date: 2019/9/23/23:02
 * description:
 *
 *  <p>
 *  * 线程池：提供一个线程队列，队列中保存所有等待状态的线程，避免了创建和销毁额外开销
 *  * <p>
 *  * 线程池体系结构：
 *  * java.utils.concurrent.Executor: 负责线程的使用与调度的根接口
 *  * |-- ExecutorService 子接口：线程池的主要接口
 *  * |-- ThreadPoolExecutor 线程池的实现类
 *  * |-- ScheduledExecutorService 子接口：负责线程的调度
 *  * |-- ScheduledThreadPoolExecutor 继承ThreadPoolExecutor.实现ScheduledExecutorService
 *  * <p>
 *  * <p>
 *  * 工具类： Executors
 *  * ExecutorService  newFixedThreadPool():创建固定大小的线程池
 *  * ExecutorService  newCacheThreadPool():缓存线程池，线程池数量不固定，可以根据需求自动更改数量
 *  * ExecutorService  newSingleThreadExecutor():创建单个线程池，线程池只有一个线程
 **/
public class TestScheduledThreadPool {
    public static void main(String args[]) throws ExecutionException, InterruptedException {
        ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(5);
        for (int i = 0; i < 5; i++) {
            Future future = scheduledExecutorService.schedule(new Callable<Integer>() {
                @Override
                public Integer call() throws Exception {
                    int num = new Random().nextInt(100);
                    System.out.println(Thread.currentThread().getName() + " : "+num);
                    return num;
                }
            },2,TimeUnit.SECONDS);
            System.out.println(future.get());
        }
        scheduledExecutorService.shutdown();
    }
}
